#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 设置根节点
    ui->treeWidget->setHeaderLabel("动物");
    // 新增顶层节点
    QTreeWidgetItem *it1 = new QTreeWidgetItem();
    // 每个节点设置多个列，并且添加到顶层节点，这里我们就设置 1 列
    it1->setText(0, "猫"); // 第 0 列
    ui->treeWidget->addTopLevelItem(it1);

    QTreeWidgetItem *it2 = new QTreeWidgetItem();
    // 每个节点设置多个列，并且添加到顶层节点
    it2->setText(0, "狗");
    ui->treeWidget->addTopLevelItem(it2);

    // 添加子节点
    QTreeWidgetItem* it3 = new QTreeWidgetItem();
    it3->setText(0, "白猫");
    it1->addChild(it3);

    QTreeWidgetItem* it4 = new QTreeWidgetItem();
    it4->setText(0, "黑猫");
    it1->addChild(it4);
}



Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_insertTopItem_clicked()
{
    // 获取输入框内容
    const QString& text = ui->lineEdit->text();
    // 构造一个 QTreeWidgetItem
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_insertItem_clicked()
{
    // 获取当前选中节点
    QTreeWidgetItem *curItem = ui->treeWidget->currentItem();
    if(curItem == nullptr) return ;
    // 获取插入信息
    const QString& text = ui->lineEdit->text();
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);
    // 插入选中节点字节点
    curItem->addChild(item);
}



void Widget::on_pushButton_deleteItem_clicked()
{
    // 获取当前选中节点
    QTreeWidgetItem *curItem = ui->treeWidget->currentItem();
    if(curItem == nullptr) return ;
    // 删除选中元素，通过父元素来删除
    QTreeWidgetItem* parent = curItem->parent();
    if(parent == nullptr) // 说明此时删除节点为顶层元素
    {
        int ind = ui->treeWidget->indexOfTopLevelItem(curItem);
        ui->treeWidget->takeTopLevelItem(ind);
    }
    else parent->removeChild(curItem);
}
